/*
 * @Author: miteng 973203639@qq.com
 * @Date: 2023-12-21 09:19:21
 * @LastEditors: shiweizhen 787632169@qq.com
 * @LastEditTime: 2025-06-26 10:03:11
 * @FilePath: /HG-dqbasic_open_platform/src/framework/utils/request.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * Copyright (c) 2024-present HBIS Digital Technology Co.,Ltd. All rights reserved.
 */
import axios, { InternalAxiosRequestConfig, AxiosResponse } from 'axios';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getToken } from '@/framework/utils/auth';
import { useUserStoreHook } from '@/framework/store/modules/user';
import { systemVariable } from '@/framework/utils/system-variable';
import { handleResponse } from 'hbisdt-design';
// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
});

// 请求拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    if (!config.headers) {
      throw new Error(
        `Expected 'config' and 'config.headers' not to be undefined`
      );
    }
    const user = useUserStoreHook();
    if (user.token) {
      config.headers.Authorization = getToken() || user.token;
      config.headers.appCode = import.meta.env.VITE_APP_CODE;
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { code, message } = response.data;
    if (code === 'C0010') return false;
    if (code === 'C0012') return true;
    if (code === '00000' || code === 200) {
      return response.data;
    } else {
      // 响应数据为二进制流处理(Excel导出)
      if (response.data instanceof ArrayBuffer) {
        return response;
      }
      if (response.data instanceof Blob) {
        return response;
      }
      const errorMessage = handleResponse(code, message);
      ElMessage({
        message: errorMessage || '系统出错',
        type: 'error'
      });
      return Promise.reject(new Error(errorMessage || 'Error'));
    }
  },
  error => {
    console.log('错误信息', error);
    if (error.response.data) {
      const { code, message } = error.response.data;
      const errorMessage = handleResponse(
        code || error.response.status,
        message
      );
      // token 过期,重新登录
      if (code === 'B0301' || code === 'A0230' || code === 'B0306') {
        ElMessageBox.confirm('当前页面已失效，请重新登录', '提示', {
          confirmButtonText: '确认',
          type: 'warning'
        }).then(() => {
          // localStorage.clear();
          // window.location.href = '/';
          const user = useUserStoreHook();
          user.resetToken();
          // @ts-expect-error微前端环境下
          if (window.rawWindow?.__MICRO_APP_BASE_APPLICATION__) {
            // @ts-expect-error微前端环境下
            window.microApp.location.reload();
          } else {
            window.location.reload();
          }
          // store.dispatch('user/resetToken').then(() => {
          //   location.reload()
          // })
        });
      }
      if (code === 'B0301') return;
      ElMessage({
        message: errorMessage,
        type: 'error',
        duration: 3 * 1000
      });

      // else {
      //   ElMessage({
      //     message: message || '系统出错',
      //     type: 'error'
      //   });
      // }
    }

    return Promise.reject(error.response.data);
  }
);

// 导出 axios 实例
export default service;

const cloud =
  import.meta.env.VITE_APP_CLOUD_ON == 'true'
    ? {
        dqBasic: '/itManage',
        notice: '/notice',
        auth: '/auth',
        file: '/file',
        usercenter: '/usercenter',
        lineMessage: '/lineMessage',
        itManage: '/itManage',
        permission: '/permission',
        openplat: '/integratedPlatform',
        businessBasic: '/businessBasic',
        sysBasic: '/sysBasic',
        process: '/workflow',
        messageCenter: '/messageCenter'
      }
    : {
        dqBasic: '',
        notice: '',
        auth: '',
        file: '',
        usercenter: '',
        lineMessage: '',
        itManage: '',
        permission: '',
        openplat: '',
        businessBasic: '',
        sysBasic: '',
        process: '',
        messageCenter: ''
      };
export { cloud };
